package com.phalanxim.ib.impl;

import com.ib.client.Contract;
import com.phalanxim.ib.BaseEWrapper;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


public class AccountDownloader extends BaseEWrapper
{
  private Map<String, Map<String, String>> snapShots
      = Collections.synchronizedMap(new HashMap<String, Map<String, String>>());
  private String brokerIdString = null;

  public Map<String, Map<String, String>> downloadAccounts() throws Exception
  {
    socket = startSession(this);
    synchronized (this)
    {
      socket.reqManagedAccts();
      while (brokerIdString == null)
      {
        wait();
      }
      for (String account : brokerIdString.split(","))
      {
        Map<String, String> acctValues = new HashMap<String, String>();
        snapShots.put(account, acctValues);
        //System.out.println("Managered Accounts: " + account + ", ");
        socket.reqAccountUpdates(true, account);
        while (acctValues.size()<89)
        {
          //System.out.println(acctValues.size());
          wait();
        }
        socket.reqAccountUpdates(false, account);
      }
    }
    socket.eDisconnect();
    return snapShots;
  }

  public void updateAccountValue(String key, String value, String currency, String accountName)
  {
    synchronized (this)
    {
      Map<String, String> acctValues = snapShots.get(accountName);
      if("USD".equals(currency))
      {
        acctValues.put(key, value);
        notify();
      }
    }
  }

  public void managedAccounts(String accountsList)
  {
    synchronized (this)
    {
      this.brokerIdString = accountsList;
      //System.out.println(accountsList);
      notify();
    }
  }

  public void receiveFA(int faDataType, String xml)
  {
    //System.out.println("receiveFA()--" + faDataType + "\n" + xml);
  }

  public void nextValidId(int orderId)
  {
    //System.out.println("nextValidId()--" + orderId);
  }

  public void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, String accountName)
  {
    //System.out.println("updatePortfolio()--" + contract.m_symbol + "--" + position + "--" + marketPrice + "--" + marketValue
        //+ "--" + averageCost + "--" + unrealizedPNL + "--" + realizedPNL + "--" + accountName);
  }

  public void updateAccountTime(String timeStamp)
  {
    //System.out.println("updateAccountTime()--" + timeStamp);
  }

}
